package com.cugmarket.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    // 时间戳 距离1970.1.1 00:00的秒数
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    // 序列号位数
    private static final long COUNT_BITS = 32;
 
    @Resource
    private StringRedisTemplate stringRedisTemplate;
 
    public long uniqueId(String KeyPrefix) {
        // 1.生成全局ID时间戳部分
        LocalDateTime now = LocalDateTime.now();
        // 当前时间距离1970.1.1 00:00的秒数
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 当前时间距离BEGIN_TIMESTAMP的秒数
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
 
        // 2.生成全局ID序列号部分
        // 2.1获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2获取自增长值
        Long count = stringRedisTemplate.opsForValue().increment(KeyPrefix + ":" + date);
        // 3.拼接时间戳和序列号并返回
        return timestamp << COUNT_BITS | count;
    }

}